package com.monolithiot.sso.controller.front;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.Authorization;
import com.monolithiot.sso.common.util.SessionAttributeUtil;
import com.monolithiot.sso.common.vo.BasicJsonResponse;
import com.monolithiot.sso.controller.ControllerSupport;
import com.monolithiot.sso.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 2018/12/12 Create by 郭文梁
 * AuthorizationController
 * 授权相关控制器
 *
 * @author 郭文梁
 * @date 2018/12/12
 */
@RestController
@RequestMapping("/front/authorization")
public class AuthorizationController implements ControllerSupport {
    private final AuthorizationService authorizationService;

    @Autowired
    public AuthorizationController(AuthorizationService authorizationService) {
        this.authorizationService = authorizationService;
    }

    /**
     * 获取当前用户的授权信息
     *
     * @param session 会话
     * @return BJR with Authorization entity
     */
    @GetMapping("/current")
    public BasicJsonResponse<Authorization> currentAuthorization(HttpSession session) {
        //获取当前授权
        Authorization authorization = SessionAttributeUtil.fromSession(session, Authorization.class, Constants.Key.SESSION_AUTHORIZATION);
        if (authorization == null) {
            return BasicJsonResponse.paramError("未授权，请先登录");
        }
        return BasicJsonResponse.ok(authorization);
    }

    /**
     * 根据token查找授权（即验证token是否有效）
     *
     * @param token 令牌
     * @return BJR with Authorization(with User)
     */
    @GetMapping("/{token}/get")
    public BasicJsonResponse<Authorization> get(@PathVariable("token") String token) {
        Authorization authorization = authorizationService.findByTokenWithUser(token);
        if (authorization == null) {
            return BasicJsonResponse.paramError("令牌无效");
        }
        return BasicJsonResponse.ok(authorization);
    }
}
